package com.sky.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;  // 添加这行导入
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.config.WeChatConfiguration;
import com.sky.service.WeChatService;  // 添加这行导入
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;  // 添加这行导入
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

@Service
@Slf4j
public class WeChatServiceImpl implements WeChatService {
    @Autowired
    private WeChatConfiguration weChatConfiguration;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ObjectMapper objectMapper; // 如果使用 Jackson

    @Override
    public String getOpenid(String code) {
        log.info("当前微信配置 appid: {}, secret: {}", weChatConfiguration.getAppid(), weChatConfiguration.getSecret());
        if (StringUtils.isBlank(code)) {
            throw new IllegalArgumentException("code 不能为空");
        }
        if (StringUtils.isBlank(weChatConfiguration.getAppid()) || StringUtils.isBlank(weChatConfiguration.getSecret())) {
            throw new IllegalStateException("微信配置未正确初始化");
        }
    
        // 修改 URL 构建方式
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String finalUrl = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                url,
                weChatConfiguration.getAppid(),
                weChatConfiguration.getSecret(),
                code);
    
        try {
            log.info("请求微信接口，URL: {}", finalUrl);
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(finalUrl, String.class);
            String body = responseEntity.getBody();
            log.info("微信接口返回: {}", body);  // 改为 info 级别，方便查看返回内容

            JSONObject jsonObject = JSON.parseObject(body); // 假设使用 fastjson
            Integer errCode = jsonObject.getInteger("errcode");
            if (errCode != null && errCode != 0) {
                String errMsg = jsonObject.getString("errmsg");
                throw new RuntimeException("微信接口调用失败: errcode=" + errCode + ", errmsg=" + errMsg);
            }

            String openid = jsonObject.getString("openid");
            if (StringUtils.isBlank(openid)) {
                throw new RuntimeException("获取openid失败: 返回数据中无openid字段");
            }
            return openid;
        } catch (RestClientException e) {
            log.error("调用微信接口失败", e);
            throw new RuntimeException("调用微信接口失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("解析微信返回数据失败", e);
            throw new RuntimeException("解析微信返回数据失败: " + e.getMessage());
        }
    }
}